#include "config.h"
#include "myFunctions.h"
#include "web.h"
#include "keyaction.h"
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <DNSServer.h>
ESP8266WebServer server;
DNSServer dnsServer;


// 标志变量
bool isConfigMode = false;
bool buttonPressedDuringBoot = false;
unsigned long buttonPressStartTime = 0;

const unsigned long CONFIG_TIMEOUT = 300000; // 5分钟配网超时
// HTML配网页面
const char configPage[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WiFi配置</title>
  <style>
    body { font-family: Arial; margin: 40px; background: #f5f5f5; }
    .container { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 400px; margin: 0 auto; }
    h2 { color: #333; text-align: center; }
    .form-group { margin-bottom: 15px; }
    label { display: block; margin-bottom: 5px; font-weight: bold; }
    input[type="text"], input[type="password"] { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; }
    button { width: 100%; padding: 12px; background: #4CAF50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
    button:hover { background: #45a049; }
    .status { padding: 10px; border-radius: 5px; margin-top: 15px; text-align: center; }
    .success { background: #d4edda; color: #155724; }
    .error { background: #f8d7da; color: #721c24; }
    .info { background: #d1ecf1; color: #0c5460; }
  </style>
</head> 
<body>
  <div class="container">
    <h2>WiFi配置</h2>
    <div class="status info">
     请配置家庭WiFi网络
    </div>
    <form action="/configure" method="POST">
      <div class="form-group">
        <label for="ssid">WiFi名称 (SSID):</label>
        <input type="text" id="ssid" name="ssid" required placeholder="输入家庭WiFi名称">
      </div>
      <div class="form-group">
        <label for="password">WiFi密码:</label>
        <input type="password" id="password" name="password" required placeholder="输入家庭WiFi密码">
      </div>
      <button type="submit">保存并连接</button>
    </form>
    <div id="status"></div>
  </div>
  <script>
    document.querySelector('form').addEventListener('submit', async function(e) {
      e.preventDefault();
      
      const formData = new FormData(this);
      const response = await fetch('/configure', {
        method: 'POST',
        body: formData
      });
      
      const result = await response.text();
      const statusDiv = document.getElementById('status');
      
      if (result.includes('success')) {
        statusDiv.className = 'status success';
        statusDiv.innerHTML = '配置保存成功！<br>设备正在重启并连接WiFi...';
      } else {
        statusDiv.className = 'status error';
        statusDiv.innerHTML = '配置保存失败，请重试';
      }
    });
  </script>
</body>
</html>
)rawliteral";

void ICACHE_FLASH_ATTR  deel_server(){
  if (isConfigMode) {
    // 配网模式处理
    dnsServer.processNextRequest();
    server.handleClient();
    // 检查配网超时
    if (millis() - buttonPressStartTime > CONFIG_TIMEOUT) {
      Serial.println("配网超时，重启设备...");
      ESP.restart();
    }
  } else {
    // 正常模式：检查WiFi连接状态
    if (WiFi.status() != WL_CONNECTED) {
      Serial.println("WiFi连接断开");
      // 可以在这里添加重连逻辑
      delay(2000);
    }
  }
  }

// 处理WiFi配置
void ICACHE_FLASH_ATTR  handleConfigure() {
  String newSSID = server.arg("ssid");
  String newPassword = server.arg("password");
  
  if (newSSID.length() > 0) {
    // 保存配置到EEPROM
    strncpy(wifiConfig.ssid, newSSID.c_str(), sizeof(wifiConfig.ssid) - 1);
    strncpy(wifiConfig.password, newPassword.c_str(), sizeof(wifiConfig.password) - 1);
    wifiConfig.configured = true;
    saveWiFiConfig();
    
    Serial.println("收到新的WiFi配置:");
    Serial.print("SSID: ");
    Serial.println(newSSID);
    Serial.print("Password: ");
    Serial.println("***"); // 不打印真实密码
    
    server.send(200, "text/plain", "success");
    delay(2000);
    
    Serial.println("重启设备并连接新WiFi...");
    ESP.restart();
  } else {
    server.send(400, "text/plain", "error: SSID不能为空");
  }
}
// 进入配网模式
void ICACHE_FLASH_ATTR enterConfigMode() {
  isConfigMode = true;
  buttonPressStartTime = millis();
  
  // 断开当前WiFi连接
  WiFi.disconnect();
  delay(100);
  
  // 创建SoftAP
  String apName = "Kucun_" + String(ESP.getChipId(), HEX);
  WiFi.softAP(apName.c_str());
  
  Serial.println("SoftAP配网模式已启动");
  Serial.print("AP名称: ");
  Serial.println(apName);
  Serial.print("请连接到此WiFi，然后访问: ");
  Serial.println("http://192.168.4.1");
  Serial.print("配网超时时间: ");
  Serial.print(CONFIG_TIMEOUT / 60000);
  Serial.println(" 分钟");
  
  // 设置DNS重定向
  dnsServer.start(53, "*", WiFi.softAPIP());
  String configHtml = getConfigPage();
  // 设置Web服务器路由
  server.on("/", HTTP_GET, [configHtml]() {
    server.send(200, "text/html", configHtml);
  });
  
  server.on("/configure", HTTP_POST, handleConfigure);
  
  server.onNotFound([configHtml]() {
    server.send(200, "text/html", configHtml);
  });
  server.begin();
}


// 连接到保存的WiFi
void ICACHE_FLASH_ATTR connectToWiFi() {
  Serial.println("尝试连接已保存的WiFi...");
  Serial.print("SSID: ");
  Serial.println(wifiConfig.ssid);
  
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiConfig.ssid, wifiConfig.password);
  
  Serial.print("连接中");
  unsigned long startTime = millis();
  
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < 20000) {
    delay(500);
    Serial.print(".");
    checKeyButton();
  }
  
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\nWiFi连接成功!");
    Serial.print("IP地址: ");
    Serial.println(WiFi.localIP());
    requestAndSaveIP();
  } else {
    Serial.println("\nWiFi连接失败!");
    Serial.println("请按住按钮重启设备进入配网模式");
  }
}

// 从EEPROM加载WiFi配置
void  ICACHE_FLASH_ATTR loadWiFiConfig() {
  EEPROM.get(0, wifiConfig);
  
  if (wifiConfig.configured && strlen(wifiConfig.ssid) > 0) {
    Serial.println("找到已保存的WiFi配置");
    Serial.print("已保存的SSID: ");
    Serial.println(wifiConfig.ssid);
  } else {
    Serial.println("未找到有效的WiFi配置");
    memset(&wifiConfig, 0, sizeof(wifiConfig));
    wifiConfig.configured = false;
  }
  
}

// 保存WiFi配置到EEPROM
void  ICACHE_FLASH_ATTR saveWiFiConfig() {
  EEPROM.put(0, wifiConfig);
  EEPROM.commit();
  Serial.println("WiFi配置已保存到EEPROM");
}

// 正确的getConfigPage实现
String ICACHE_FLASH_ATTR getConfigPage() {
  String html;
  // 从PROGMEM读取HTML内容
  size_t len = strlen_P(configPage);
  html.reserve(len + 1);
  
  for (size_t i = 0; i < len; i++) {
    html += (char)pgm_read_byte_near(configPage + i);
  }
  return html;
}
